﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using EvidenceLib.System;
using EvidenceService.AF;
using EvidenceService.Core;
using NHibernate;

namespace EvidenceWeb
{
    /// <summary>
    /// AttachmentUpload 的摘要说明
    /// </summary>
    public class AttachmentUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";

                int CaseId = int.Parse(context.Request["CaseId"]);
                int billType = int.Parse(context.Request["billType"]);
                int billId = int.Parse(context.Request["billId"]);
                int deptId = int.Parse(context.Request["deptId"]);
                int userId = int.Parse(context.Request["userId"]);

                string description = context.Request["description"];


                HttpPostedFile postedFile = context.Request.Files[0];

                string attachmentPath = ConfigurationManager.AppSettings["AttachmentDirectory"];

                string path = HttpContext.Current.Server.MapPath(attachmentPath) + billType + "/" + billId + "/";

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                string fullFileName = path + "/" +Path.GetFileName( postedFile.FileName);

                postedFile.SaveAs(fullFileName);
                
                FileInfo file = new FileInfo(fullFileName);

                string url = "/" + attachmentPath + "/" + billType + "/" + billId + "/"+file.Name;

                using (ISession session = HbmSessionFactory.GetSession())
                {
                    AttachmentService svr = new AttachmentService(session);

                    svr.SaveOrUpdate(CaseId,billType,billId, file.Name, file.Extension, url, description,file.Length, deptId,userId);
                }
                context.Response.Write("上传成功!");
                context.Response.Flush();

            }
            catch (Exception ex)
            {
                //context.Response.Clear();
                context.Response.Write("上传失败!"+ex.Message);
                context.Response.Flush();

                throw ex;
            }
            finally
            {
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}